var WebSocketServer = require('websocket').server;
var https = require('https');
var fs = require('fs');

var tlsOptions = {
    key: fs.readFileSync(__dirname + '/ssl/2_ws.tdreamer.cc.key'),
    cert: fs.readFileSync(__dirname + '/ssl/1_ws.tdreamer.cc_bundle.crt')
    //  ciphers:"ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE"
};

var httpsServer = https.createServer(tlsOptions, (app) => {
    res.writeHead(403);//403即可  
    res.end("This is a  WebSockets server!\n");
    console.log((new Date()) + ' Received request for ' + app);
}).listen(443);

var ws = new WebSocketServer({
    httpServer: httpsServer
});

function originIsAllowed(origin) {
    console.log(origin + ' Connection !')
    if (origin == 'http://762255896.appservice.open.weixin.qq.com') {
        return true;
    } else {
        return false;
    }
}

ws.on('request', function (request) {
    if (!originIsAllowed(request.origin)) {
        // Make sure we only accept requests from an allowed origin 
        request.reject();
        console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
        return;
    }

    var connection = request.accept('', request.origin);
    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function (message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF(message.utf8Data);
        } else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function (reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });

    // 时间发送
    setInterval(function () {
        connection.sendUTF((new Date()));
    }, 1000)
});